//
//  AppDelegate.m
//  industry
//
//  Created by xl on 2020/11/10.
//  Copyright © 2020 Haier. All rights reserved.
//

#import "AppDelegate.h"
#import "AppStartUpConfig.h"
#import "XLLoginRegisterVC.h"
#import "XLNetworking.h"
#import "XLUserDefaults.h"
#import "YQCheckOtherLogin.h"

@interface AppDelegate ()

@property (nonatomic, strong) AppStartUpConfig *startUpConfig;

@end

@implementation AppDelegate

+ (AppDelegate *)sharedInstance {
    return [UIApplication sharedApplication].delegate;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    //界面初始配置
    [self.startUpConfig configAppWithApplication:application launchOptions:launchOptions];
    
    return YES;
}

#pragma mark - 通知相关
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    //注册APNS成功，注册deviceToken
    [[PushService sharedService] setDeviceToken:deviceToken];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

#pragma mark - setter/getter
- (AppStartUpConfig *)startUpConfig {
    if (!_startUpConfig) {
        _startUpConfig = [AppStartUpConfig new];
    }
    return _startUpConfig;
}


#pragma 微信相关
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [WXApi handleOpenURL:url delegate:self];
}

-(BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler{
    
    
    return [WXApi handleOpenUniversalLink:userActivity delegate:self];
}

-(void) onReq:(BaseReq*)req
{
    if([req isKindOfClass:[GetMessageFromWXReq class]])
    {
        // 微信请求App提供内容， 需要app提供内容后使用sendRsp返回
        NSString *strMsg = @"微信请求App提供内容，App要调用sendResp:GetMessageFromWXResp返回给微信";
        XLLog(@"微信请求App显示内容 %@",strMsg);
       
    }
    else if([req isKindOfClass:[ShowMessageFromWXReq class]])
    {
        ShowMessageFromWXReq* temp = (ShowMessageFromWXReq*)req;
        WXMediaMessage *msg = temp.message;
        
        //显示微信传过来的内容
        WXAppExtendObject *obj = msg.mediaObject;
        
        NSString *strMsg = [NSString stringWithFormat:@"标题：%@ \n内容：%@ \n附带信息：%@ \n bytes\n\n", msg.title, msg.description, obj.extInfo];
        
        XLLog(@"微信请求App显示内容 %@",strMsg);
    }
    else if([req isKindOfClass:[LaunchFromWXReq class]])
    {
        //从微信启动App
        NSString *strMsg = @"这是从微信启动的消息";
        XLLog(@"%@",strMsg);
       
    }
}

-(void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[SendAuthResp class]])
    {
        SendAuthResp * respond = (SendAuthResp *) resp;
         
        NSLog(@"请求授权返回respond:%@---code:%@----errCode:%d",respond,respond.code,respond.errCode);
        
        if (resp.errCode == 0) {
            BOOL state = respond.state.boolValue;
            [self repuest:respond.code andStaffState:state];
        }else{
            XLLog(@"微信请求授权失败errCode：%d",resp.errCode);
            [XLToast showErrorMessage:[NSString stringWithFormat:@"微信请求授权失败%d",resp.errCode]];
        }
        
       
        
    }
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        XLLog(@"消息分享成功");
    }
}

-(void) repuest:(NSString *)code andStaffState:(BOOL)state {
    NSString * url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WXAPP_ID,WXAPP_SECRET,code];
    [XLNetworking getWithUrl:url params:nil success:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, id response) {
        
        NSDictionary * dict = (NSDictionary *)response;
        
        if (dict[@"errcode"]) {
            NSLog(@"获取微信openID失败%@",response);
            return;
        }
        
        NSLog(@"获取微信openID成功%@",response);
        [YQCheckOtherLogin loginRepuest:dict[@"openid"] withType:XLLoginBindWeiXin andStaffState:state andCurrentVC:self.currentTopController];
        
        } fail:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, id response, NSError *error) {
            NSLog(@"获取微信openID失败%@，%@",error,response);
            [XLToast showErrorMessage:[NSString stringWithFormat:@"获取微信openID失败%@，%@",error,response]];
        }];
}






@end
